package com.jd.dict.dao;

import com.jd.dict.config.ConfigClass;

import java.sql.*;
import java.util.List;

/**
 * Created by liuhaiming on 2017/7/28.
 */
public class BaseDao {
    private Connection conn = null;
    private Statement stmt = null;

    public BaseDao() {
        try {
            if (conn == null) {
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://" + ConfigClass.IP + ":" + ConfigClass.PORT + "/" + ConfigClass.DB_NAME + "?user=" + ConfigClass.USERNAME + "&password=" + ConfigClass.PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
                conn = DriverManager.getConnection(url);
            }

            conn.setAutoCommit(false);
            stmt = conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConn() {
        return conn;
    }

    public void commit() {
        try {
            conn.commit();
        } catch (SQLException e) {
            rollback();
        }
    }

    public ResultSet queryBySql(String sql) throws SQLException {
        ResultSet rs = stmt.executeQuery(sql);

        return rs;
    }

    public void addBatch(String sql) throws SQLException, Exception {
        stmt.addBatch(sql);
    }

    public void clearBatch() throws SQLException, Exception {
        stmt.clearBatch();
    }

    public void excuteBatch() throws SQLException {
        stmt.executeBatch();
    }

    /**
     *
     */
    public void rollback() {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
}
